/*
 * fuzuli : A general purpose interpreter
 * Copyright (C) 2013 Mehmet Hakan Satman <mhsatman@yahoo.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package Interpreter;

import java.util.ArrayList;

public class EvalExpression extends Expression {

    public EvalExpression(ArrayList<Expression> exprs) {
        this.exprs = exprs;
    }

    @Override
    public Object eval(Environment e) {
        Object param = this.exprs.get(0).eval(e);
        if (param instanceof ExpressionExpression) {
            ExpressionExpression exp = (ExpressionExpression) param;
            Object result = null;
            for (int i = 0; i < exp.exprs.size(); i++) {
                result = exp.exprs.get(i).eval(e);
            }
            return (result);
        } else if (param instanceof String) {
            Parser parser = new Parser(param.toString());
            Expression exp = null;
            Object result = null;
            while (true) {

                try {
                    exp = parser.getNextExpression();
                } catch (Exception exc) {
                    break;
                }

                if (exp == null) {
                    break;
                }

                try {
                    result = exp.eval(e);
                } catch (Exception exc) {
                    System.out.println("eval: Runtime Error: " + exc.toString());
                    exc.printStackTrace();
                    System.exit(-1);
                }
            }
            return (result);
        }
        return (null);
    }
}
